// pages/Home/VehicleDetail/VehicleDetail.js
import { queryTravelVehiclePic , queryTravelVehicleStore , queryTravelVehicleStoreConfig , queryTravelVehicleDetail } from '../../../api/vehicle';
import { addZero , getDateWeek } from '../../../utils/util';
var QQMapWX = require('../../../common/qqmap-wx-jssdk.min.js');
var qqmapsdk;
const regeneratorRuntime = require('../../../common/runtime');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    item: {},
    rentCarStartYear: '',
    rentCarEndYear: '',
    rentCarStartCurrent: '',
    rentCarStartDate: '', // 开始时间的日期
    rentCarStartWeek: '', // 开始时间的星期
    rentCarStartTime: '', // 开始租车时间
    rentCarDateDiff: '', // 租还间隔时间
    rentCarEndCurrent: '',
    rentCarEndDate: '', // 还车时间的日期
    rentCarEndWeek: '', // 还车时间的星期
    rentCarEndTime: '', // 还车时间
    minDate: new Date().getTime(),
    showStartTimePop: false,
    showEndTimePop: false,
    bannerList: [], // 轮播图列表
    detailList: [], // 详情图列表
    pickUpLocation: '三亚机场', // 取车地点
    province: '',
    city: '',
    country: '',
    town: '',
    provinceCity: '', // 省市区
    latitude: '',
    longitude: '',
    detailedAddress: '', // 详细地址
    storeList: [], // 门店列表
    infoCont: [], // 基本信息
    configCont: [], // 配置信息
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let _this = this;
    qqmapsdk = new QQMapWX({
      key: 'MEZBZ-6D3O4-JPJU6-XRZRL-LH73V-PYFUZ'
    });
    if(options.item){
      var item = JSON.parse(options.item);
      console.log(item,'item')
      _this.setData({
        item: item,
      })
      wx.setNavigationBarTitle({
        title: item.name,
      })
      _this._queryTravelVehiclePic({type: '0'});
      _this._queryTravelVehiclePic({type: '1'});
      _this._queryTravelVehicleStore();
      _this._queryTravelVehicleDetail({type: '0'});
      _this._queryTravelVehicleDetail({type: '1'});
    }
    _this.setData({
      rentCarStartDate: wx.getStorageSync('rentCarStartDate'),
      rentCarStartTime: wx.getStorageSync('rentCarStartTime'),
      rentCarStartWeek: wx.getStorageSync('rentCarStartWeek'),
      rentCarEndDate: wx.getStorageSync('rentCarEndDate'),
      rentCarEndTime: wx.getStorageSync('rentCarEndTime'),
      rentCarDateDiff: wx.getStorageSync('rentCarDateDiff'),
      rentCarEndWeek: wx.getStorageSync('rentCarEndWeek'),
      rentCarStartCurrent: wx.getStorageSync('rentCarStartCurrent'),
      rentCarEndCurrent: wx.getStorageSync('rentCarEndCurrent'),
      rentCarStartYear: wx.getStorageSync('rentCarStartYear'),
      rentCarEndYear: wx.getStorageSync('rentCarEndYear'),
    })
    if (wx.onNeedPrivacyAuthorization) {
      wx.onNeedPrivacyAuthorization((resolve) => {
        console.log('触发弹窗')
        // 触发弹窗
        _this.setData({
          showPrivacyAuthor: true,
        })
        _this.resolvePrivacyAuthorization = resolve
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  // 获取车辆图片信息
  _queryTravelVehiclePic({type}){
    let _this = this;
    queryTravelVehiclePic({type: type,vehicleId: _this.data.item.id,size: 99})
    .then(res => {
      if(res.success){
        let arr = [];
        for (let index = 0; index < res.data.content.length; index++) {
          const item = res.data.content[index];
          arr.push(item.imageUrl);
        }
        if(type == '1'){
          _this.setData({
            bannerList: arr,
          })
        }else{
          _this.setData({
            detailList: arr,
          })
        }
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 选择租车地点
  selPickUpLocation(){
    let _this = this;
    wx.chooseLocation({
      success: (res)=>{
        console.log(res,'res')
        qqmapsdk.reverseGeocoder({
          location: {
            'latitude': res.latitude,
            'longitude': res.longitude
          },
          success: (res)=> {
            var res = res.result;
            console.log(res,'解析地址')
            _this.setData({
              longitude: res.location.lng,
              latitude: res.location.lat,
              province: res.address_component.province,
              city: res.address_component.city,
              country: res.address_component.district,
              town: res.address_reference.town ? res.address_reference.town.title : res.address_component.street,
              detailedAddress: res.address_component.street_number ? res.address_component.street + res.address_component.street_number : res.formatted_addresses.recommend ? res.formatted_addresses.recommend : res.address_component.street,
              pickUpLocation: `${res.address_component.province}/${res.address_component.city}/${res.address_component.district}/${res.address_reference.town ? res.address_reference.town.title : res.address_component.street}/${res.address_component.street_number ? res.address_component.street + res.address_component.street_number : res.formatted_addresses.recommend ? res.formatted_addresses.recommend : res.address_component.street}`,
              getLat: false,
            })
            _this._queryTravelVehicleStore();
          },
          fail: (err)=> {
            console.log(err,'解析错误')
          }
        })
      }
    })
  },
  showStart(){
    this.setData({
      showStartTimePop: true
    })
  },
  startConfirm(e){
    console.log('start',e)
    var date = new Date(e.detail)
    console.log(date,'date')
    var year = date.getFullYear();
    var month = addZero(date.getMonth() + 1);
    var day = addZero(date.getDate());
    var hour = addZero(date.getHours());
    var min = addZero(date.getMinutes())
    var week = `星期${getDateWeek(date)}`;
    this.setData({
      showStartTimePop: false,
      showEndTimePop: true,
      rentCarStartCurrent: e.detail,
      rentCarStartDate: `${month}-${day}`,
      rentCarStartTime: `${hour}:${min}`,
      rentCarStartWeek: week,
      rentCarEndYear: year,
    })
  },
  startCancel(){
    this.setData({
      showStartTimePop: false,
    })
  },
  showEnd(){
    this.setData({
      showEndTimePop: true,
    })
  },
  endConfirm(e){
    console.log('end',e)
    var date = new Date(e.detail)
    console.log(date,'date')
    var year = date.getFullYear();
    var month = addZero(date.getMonth() + 1);
    var day = addZero(date.getDate());
    var hour = addZero(date.getHours());
    var min = addZero(date.getMinutes())
    if(e.detail - this.data.rentCarStartCurrent < 30 * 60 * 1000){
      wx.showToast({
        title: '租车时间和换成时间暂无法选择同一时间段',
        icon: 'none',
      });
      return;
    } 
    var diffTime = e.detail - this.data.rentCarStartCurrent + 60000;
    var diffDay = parseInt(diffTime / 24 / 3600 / 1000);
    var endWeek = `星期${getDateWeek(date)}`;
    this.setData({
      showEndTimePop: false,
      rentCarEndYear: year,
      rentCarEndCurrent: e.detail,
      rentCarEndDate: `${month}-${day}`,
      rentCarEndTime: `${hour}:${min}`,
      rentCarDateDiff: diffDay,
      rentCarEndWeek: endWeek,
    })
    wx.setStorageSync('rentCarEndCurrent', e.detail);
    wx.setStorageSync('rentCarEndDate', this.data.rentCarEndDate);
    wx.setStorageSync('rentCarEndTime', this.data.rentCarEndTime);
    wx.setStorageSync('rentCarDateDiff', this.data.rentCarDateDiff);
    wx.setStorageSync('rentCarStartCurrent', this.data.rentCarStartCurrent);
    wx.setStorageSync('rentCarStartDate', this.data.rentCarStartDate);
    wx.setStorageSync('rentCarStartTime', this.data.rentCarStartTime);
    wx.setStorageSync('rentCarStartYear', this.data.rentCarStartYear);
    wx.setStorageSync('rentCarEndYear', this.data.rentCarEndYear);
  },
  endCancel(){
    this.setData({
      showStartTimePop: true,
      showEndTimePop: false
    })
  },
  onClose(){
    this.setData({
      showStartTimePop: false,
      showEndTimePop: false,
    })
  },
  // 获取租车商家信息
  _queryTravelVehicleStore(){
    let _this = this;
    queryTravelVehicleStore({province: _this.data.province,city: _this.data.city,area: _this.data.country,size: 99})
    .then(async res => {
      if(res.success){
        let arr = [];
        for (let index = 0; index < res.data.content.length; index++) {
          const element = res.data.content[index];
          element.tagList = element.tag ? element.tag.split(',') : []
          element.logoUrlList = element.logoUrl ? element.logoUrl.split(',') : []
          let config = await _this._queryTravelVehicleStoreConfig({storeId: element.id});
          element.config = config;
          arr.push(element);
        }
        _this.setData({
          storeList: arr,
        })
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 获取租车门店配置信息
  _queryTravelVehicleStoreConfig({storeId}){
    let _this = this;
    return new Promise((resolve,reject) => {
      queryTravelVehicleStoreConfig({vehicleId: _this.data.item.id,storeId: storeId})
      .then(res => {
        if(res.success){
          resolve(res.data.content.length > 0 ? res.data.content[0] : {});
        }else{
          reject(res.errMessage);
        }
      })
    })
  },
  // 订车
  submitStore(e){
    console.log(e,'e')
    const { province , city , country , town , detailedAddress , item } = this.data;
    wx.navigateTo({
      url: `/pages/Home/VehicleSubmit/VehicleSubmit?province=${province}&city=${city}&country=${country}&town=${town}&detailedAddress=${detailedAddress}&item=${JSON.stringify(item)}&store=${JSON.stringify(e.detail)}`,
    })
  },
  // 获取车辆基本信息
  _queryTravelVehicleDetail({type}){
    let _this = this;
    queryTravelVehicleDetail({vehicleId: _this.data.item.id,type: type})
    .then(res => {
      if(res.success){
        if(type == '0'){
          _this.setData({
            infoCont: res.data.content
          })
        }else{
          _this.setData({
            configCont: res.data.content
          })
        }
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
})